package thread.ThreadPool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    //提交任务
    public void submit(Runnable task) throws InterruptedException {
        queue.put(task);
    }

    //线程池
    public MyThreadPool(int vip) {
        for(int i = 0; i < vip; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //从阻塞队列中取出任务并执行
                    try {
                        Runnable task = queue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
        }
    }
}

class Main {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool threadPool = new MyThreadPool(10);
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                for(int i = 1; i <= 100; i++) {
                    System.out.println("线程" + Thread.currentThread().getName() + "执行了任务:" + i + "~");
                }
            }
        });
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                for(int i = 101; i <= 200; i++) {
                    System.out.println("线程" + Thread.currentThread().getName() + "执行了任务:" + i + "~");
                }
            }
        });
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                for(int i = 201; i <= 300; i++) {
                    System.out.println("线程" + Thread.currentThread().getName() + "执行了任务:" + i + "~");
                }
            }
        });

    }
}



